import { Component, OnInit } from '@angular/core';
import { NetService } from './../../services/net.service';
import { NzMessageService } from 'ng-zorro-antd';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';
interface Menu {
  _id: string;
  name: string;
  icon: string;
  code: string;
  link: string;
  parentId: string;
  roles: Array<string>;
}

interface AntdMenu {
  key?: string;
  title?: string;
  icon?: string;
  code?: string;
  parentId?: string;
  roles?: Array<any>;
  link?: string;
}

interface Role {
  code: string;
  name: string;
  _id: string;
}

@Component({
  selector: 'app-menu-list',
  templateUrl: './menu-list.component.html',
  styleUrls: ['./menu-list.component.scss']
})
export class MenuListComponent implements OnInit {

  public menuData: Array<Menu>;
  public currentMenu: AntdMenu;
  public menuForm: FormGroup;
  public treeData = [];
  public notTopMenus: Array<Menu> = [];

  public roleData: Array<Role> = [];
  public currentRolesOptions = [];

  public canDeal = false;
  public modalVisible = false;

  constructor(
    private net: NetService,
    private fb: FormBuilder,
    private nzmsg: NzMessageService
  ) { }
  // 处理角色数据;
  get checkedRoleData() {
    const newRoels = [];
    this.roleData.forEach(item => {
      const role = {
        label: item.name,
        value: item.code,
        checked: false,
        menuId: ''
      };
      newRoels.push(role);
    });
    return newRoels;
  }
  // 处理表格中数据
  get formRoles () {
    const arr = [];
    this.roleData.forEach(item => {
      const obj = {};
      obj['label'] = item.name;
      obj['value'] = item.code;
      obj['checked'] = false;
      arr.push(obj);
    });
    return arr;
  }
  // 当前菜单是否为空对象
  get currentMenuIsEmpty() {
    return Object.keys(this.currentMenu).length === 0;
  }
  // 递归处理菜单数据
  handleMenu(menus: Array<Menu>, parentId: string = '') {
    if (!menus || menus.length === 0) { return []; }
    const levelMenus = [];
    const nextLevelMenus = [];
    menus.forEach(item => {
      if (item.parentId === parentId) {
        levelMenus.push(item);
      } else {
        nextLevelMenus.push(item);
      }
    });
    const newMenu = [];
    levelMenus.forEach(item => {
      newMenu.push({
        key: item._id,
        title: item.name,
        icon: item.icon || '',
        code: item.code,
        link: item.link,
        roles: item.roles,
        parentId: item.parentId,
        isLeaf: nextLevelMenus.length === 0,
        children: this.handleMenu(nextLevelMenus, item._id)
      });
    });
    return newMenu;
  }
  // 点击树组件
  treeClick(item) {
    const id = item.node.origin.key;
    const roles = item.node.origin.roles;
    this.canDeal = true;
    this.currentMenu = item.node.origin;
    this.currentRolesOptions = [];
    this.checkedRoleData.forEach(im => {
      const tem = {
        label: im['label'],
        value: im['value'],
        checked: roles.includes(im['value']),
        menuId: id
      };
      this.currentRolesOptions.push(tem);
    });
  }

  changeRole(data) {
    const roles = [];
    let id = '';
    data.forEach(item => {
      if (!id) { id = item['menuId']; }
      if (item['checked']) {
        roles.push(item['value']);
      }
    });
    this.currentMenu.roles = roles;
  }

  async modify() {
    const menu = {
      _id: this.currentMenu.key,
      name: this.currentMenu.title,
      code: this.currentMenu.code,
      icon: this.currentMenu.icon,
      link: this.currentMenu.link,
      parentId: this.currentMenu.parentId,
      roles: this.currentMenu.roles
    };
    await this.net.put('/api/menus', menu);
    this.getMenus();
    this.nzmsg.success('修改菜单成功!');
  }

  async delMenu() {
    if (!this.currentMenu) {
      this.nzmsg.error('请先选择需要操作的菜单!');
    }
    const result = await this.net.delete(`/api/menus/${this.currentMenu.key}`);
    if (result) {
      this.nzmsg.success('删除菜单成功！');
      this.getMenus();
    }
  }
  // 添加菜单
  addMenu() {
    this.menuForm.reset({
      link: null,
      name: null,
      code: null,
      roles: this.formRoles
    });
    this.modalVisible = true;
    this.notTopMenus = [{name: '无', _id: '', code: '', icon: '', link: '', parentId: '', roles: []}];
    this.notTopMenus.push(...this.menuData);
  }
  // 取消添加菜单模态窗
  modalCancel() {
    this.modalVisible = false;
  }
  // 添加菜单模态窗确定添加
  modalOk() {
    Object.keys(this.menuForm.controls).forEach(item => {
      this.menuForm.controls[item].markAsDirty();
      this.menuForm.controls[item].updateValueAndValidity();
    });
    if (this.menuForm.valid) {
      this.modalVisible = false;
      this.submitForm();
    }
  }
  // 提交表单
  async submitForm() {
    const allRoles = this.menuForm.get('roles').value;
    const roles = [];
    allRoles.forEach(item => {
      if (item.checked) { roles.push(item.value); }
    });
    const cond = {
      name: this.menuForm.get('name').value,
      code: this.menuForm.get('code').value,
      icon: this.menuForm.get('icon').value,
      link: this.menuForm.get('link').value || '',
      parentId: this.menuForm.get('parentMenu').value || '',
      roles: roles
    };
    const result = await this.net.post('/api/menus', cond);
    if (result) {
      this.nzmsg.success('创建菜单成功！');
      this.getMenus();
    }
  }
  // 获取菜单
  async getMenus() {
    const result = await this.net.get('/api/menus');
    if (result) {
      this.menuData = result['data'];
      this.treeData = this.handleMenu(this.menuData);
    }
  }
  // 获取角色
  async getRoles() {
    const result = await this.net.get('/api/roles');
    if (result) {
      this.roleData = result['data'];
    }
  }

  async ngOnInit() {
    this.menuForm = this.fb.group({
      link: [null],
      roles: [[]],
      icon: [''],
      name: [null, [Validators.required]],
      code: [null, [Validators.required]],
      parentMenu: ['']
    });
    this.currentMenu = {};
    this.getMenus();
    this.getRoles();
  }

}
